import 'dart:io';
import 'package:bruno/bruno.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:native_dart_package/http/env/env_model.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:native_dart_package/model/user_auth.dart';
import 'package:native_dart_package/store/sp_store.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:umeng_push_sdk/umeng_push_sdk.dart';
import 'package:yt_devops/components/event_bus_util/eventbus_util.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/network_image_load/image_utils.dart';
import 'package:yt_devops/components/tips.dart';
import 'package:yt_devops/components/yt_input.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/log_record/db_manager.dart';
import 'package:yt_devops/model/user_model.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/auth/auth_services.dart';
import 'package:yt_devops/services/user/user_services.dart';
import 'package:yt_devops/user_entity_manager.dart';
import 'package:yt_devops/utils/constants/store_keys.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/navigate_utils.dart';
import 'package:yt_devops/utils/umeng/helper.dart';
import 'package:yt_devops/utils/umeng/pusher.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:native_dart_package/native_dart_package.dart' as client;

class LoginController extends GetxController {
  // 是否已经同意协议
  bool isAgree = false;

  // 是否可提交
  bool enable = false;

  YtSearchTextController searchTextController = YtSearchTextController();

  TextEditingController nameController = TextEditingController();

  TextEditingController pwdController = TextEditingController();

  FocusNode focusNode = FocusNode()..unfocus();

  FocusNode pwdFocusNode = FocusNode()..unfocus();

  GlobalKey leftKey = GlobalKey();

  final authServices = Get.find<AuthServices>();
  List<String> environmentConditions = [
    'https://192.168.3.4',
    'https://192.168.3.47',
    'https://192.193.134.121:443',
    'https://103.191.242.231:443',
    'https://ytoss.yotaienergy.com',
    'https://183.47.48.60:40008',
    'https://183.47.48.60:40010',
  ];
  int selectedRoleIndex = -1;
  String environmentString = 'https://ytoss.yotaienergy.com';
  late SharedPreferences prefs;
  bool isRelease = true;
  bool isShowPop = false;
  int selectedIndex = 0; //切换语言的索引
  UserServices services = Get.put(UserServices());
  List<String> languageList = ['中文(简体)', 'English'];
  List<String> languageStringList = ['zh-CN', 'en-US'];
  GetStorage storage = GetStorage();
  @override
  void onInit() {
    super.onInit();
    String? languageCode = Get.locale?.languageCode;
    if (languageCode != null && languageCode.toString() == 'en') {
      selectedIndex = 1;
    }
    changeLanguage(selectedIndex);
    if (kReleaseMode) {
      isRelease = true;
    } else {
      isRelease = false;
      getEnvironment();
    }
    nameController.text = UserEntityManager().userModel.loginedAccount ?? '';

    nameController.addListener(() {
      if (focusNode.hasFocus) {
        if (nameController.text.isNotEmpty) {
          searchTextController.isClearShow = true;
        }
      }
    });
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        if (nameController.text.isNotEmpty) {
          searchTextController.isClearShow = true;
        }
      }
    });
  }

  @override
  void onReady() {}

  @override
  void onClose() {
    focusNode.dispose();
    // nameController.dispose();
  }

  ///切换语言
  changeLanguage(int index) async {
    if (index == selectedIndex) {
      //如果选择索引和当前索引一致不做任何操作
      return;
    }
    var locale = const Locale('zh', 'CN');
    if (index == 1) {
      locale = const Locale('en', 'US');
    }
    storage.write('changeLocale', locale.languageCode.toString());
    selectedIndex = index;
    FuncUtils.changeLocale(locale: locale);
    EventBusUtil.getInstance().fire(SwitchLanguage());
    ListTips.resetRefresh();
    isShowPop = false;
    update();
  }

  void getEnvironment() async {
    prefs = await SharedPreferences.getInstance();
    environmentString = prefs.getString('currentEnvironment') ??
        'https://ytoss.yotaienergy.com';
    for (int i = 0; i < environmentConditions.length; i++) {
      if (environmentConditions[i] == environmentString) {
        selectedRoleIndex = i;
        // environmentString = environmentConditions[selectedRoleIndex];
        break;
      }
    }
    _changeEnvironmentData(environmentString);
  }

  showPop() {
    isShowPop = !isShowPop;
    update();
  }

  agreePolicy(int index, bool status) {
    isAgree = status;
    update();
    if (status) {
      Get.back();
    }

    UmengHelper.agree().then((value) {
      UmengPusher.register();
    });
  }

  textOnchange(String text) {
    if (pwdController.text.isNotEmpty &&
        nameController.text.isNotEmpty &&
        text.isNotEmpty) {
      enable = true;
    } else {
      enable = false;
    }

    update();
  }

  login(BuildContext context) {
    if (!isAgree) {
      return BrnToast.show(
          '${ResKey.readAndAgree.tr}《${ResKey.privatePolicy.tr}》', context,
          duration: BrnDuration.short,
          verticalOffset: 100,
          textStyle: TextStyle(fontSize: 14.sp));
    }
    loginAction(nameController.text, pwdController.text, context);
  }

  ///游客登录
  visitorLogin(BuildContext context) {
    loginAction('游客', 'vi123456', context);
  }

  loginAction(String username, String password, BuildContext context) async {
    FocusScope.of(context).unfocus();
    //获取deviceToken
    var deviceToken = await UmengPusher.getDeviceToken();
    UmengPusher.setTokenCallback();
    //获取版本号
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String version = packageInfo.version;
    //发送请求
    var params = {
      'username': username,
      'password': password,
      'deviceToken': deviceToken,
      'version': version,
      'lang': languageStringList[selectedIndex],
      'platform': Platform.isAndroid ? 0 : 1
    };

    showLoading(toast: ResKey.loading.tr);
    var value = await authServices.login(params, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    //存token
    UserEntityManager().saveAuth(UserAuth(token: value['access_token']));

    //将版本号存到本地，用于每次打开app做比对
    SpSotre.instance.setString(StoreKeys.version, version);
    // 打tag
    authServices.pushTags(
      onError: (error) {
        return false;
      },
    ).then((value) async {
      await UmengPusher.removeTags();
      List<String> tags = [];

      value.forEach((e) {
        tags.add(e.toString());
      });
      UmengPusher.addTags(tags);
    });
    await UserEntityManager().getInfo();

    var path = NavigateUtils.getHomeTabByRole();
    Get.offAllNamed(path);
  }

  toPolicy() async {
    var result = await DBManager().findAll();
    Log.d('result===$result');
    Get.toNamed(RouterPath.privatePolicy);
  }

  ///测试环境允许切换测试或者生产环境,切换环境需要同时切换网络图片地址和本地保存当前选择的环境
  changeEnvironment() {
    showDialog(
        context: Get.context!,
        builder: (_) => StatefulBuilder(
              builder: (context, state) {
                return BrnSingleSelectDialogWidget(
                    isClose: true,
                    title: ResKey.checkEnv.tr,
                    conditions: environmentConditions,
                    checkedItem: selectedRoleIndex == -1
                        ? null
                        : environmentConditions[selectedRoleIndex],
                    submitText: ResKey.sure.tr,
                    isCustomFollowScroll: true,
                    themeData: BrnDialogConfig(
                        dialogWidth: 300.w,
                        contentTextStyle: BrnTextStyle(fontSize: 16.sp)),
                    onItemClick: (BuildContext context, int index) {
                      selectedRoleIndex = index;

                      state(() {});
                    },
                    onSubmitClick: (data) {
                      environmentString = data ?? '';
                      saveEnvironment(environmentString);
                      update();
                    });
              },
            ));
  }

  //保存切换后的数据
  Future<void> saveEnvironment(String environment) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString('currentEnvironment', environment);
    _changeEnvironmentData(environment);
  }

  ///切换环境数据
  _changeEnvironmentData(String environment) {
    Future.delayed(const Duration(milliseconds: 500)).then((value) async {
      EnviromentModel environmentModel = await Configs().environment;
      environmentModel.api = environment;
      Configs.httpClient = client.HTTPClient(environment: environmentModel);
      Configs.enviromentModel = environmentModel;
      ImageUtils.initialization(environment);
      update();
    });
  }
}
